#include "OutputData.h"
#include "QXlsxQt6/xlsxdocument.h"
#include "ui_OutputData.h"
#include <QTreeView>
#include "ElementTreeModel.h"
#include <QModelIndex>
#include <QFileDialog>
#include <qmessagebox.h>
OutputData::OutputData(ElementTreeModel* treeModel,QListWidget* listWidget,QWidget *parent) :
    QDialog(parent),
    m_treeModel(treeModel),
    m_listWidget(listWidget),
    ui(new Ui::OutputData)
{
    ui->setupUi(this);
    setWindowTitle("数据导出");
    // ui->comboBoxType->addItem("csv");
    // ui->comboBoxType->addItem("xlsx");
    connect(ui->comboBoxFileName, &QComboBox::currentIndexChanged, this, &OutputData::onComboBoxFileNameIndexChanged);
    connect(ui->pushButtonSelect,&QPushButton::clicked,this,&OutputData::onPushButtonSelectClicked);
    connect(ui->pushButtonClear,&QPushButton::clicked,this,&OutputData::onPushButtonClearClicked);
    connect(ui->pushButtonRemove,&QPushButton::clicked,this,&OutputData::onPushButtonRemoveClicked);
    connect(ui->pushButtonExport,&QPushButton::clicked,this,&OutputData::onPushButtonExportClicked);
    // 假设你已经有一个 QTreeView 的指针 m_treeView
    if (m_treeModel) {
        for(int i=0;i<m_treeModel->rowCount();++i){
            auto item=(ElementTreeItem*)m_treeModel->index(i,0).internalPointer();
            if(item){
                ui->comboBoxFileName->addItem(item->value(Qt::DisplayRole).toString());
            }
        }
    }
}

OutputData::~OutputData()
{
    delete ui;
}

void OutputData::onComboBoxFileNameIndexChanged(int index)
{
    if(m_treeModel){
        m_selecttingMap.clear();
        auto item=(ElementTreeItem*)m_treeModel->index(index,0).internalPointer();
        ui->listWidgetSelecting->clear();
        if(!item){
            return;
        }
        ui->listWidgetSelecting->addItem(item->value(ElementTreeItem::TimeName).toString());
        m_selecttingMap[ui->listWidgetSelecting->item(0)]=item;
        for(int i=0;i<item->childrenCount();++i){
            auto child=item->child(i);
            if(child->have(Qt::DisplayRole)){
                ui->listWidgetSelecting->addItem(child->value(Qt::DisplayRole).toString());
                m_selecttingMap[ui->listWidgetSelecting->item(i+1)]=child;
            }//
        }
    }
}

void OutputData::onPushButtonSelectClicked()
{
    auto item = ui->listWidgetSelecting->currentItem();
    if(item){
        ui->listWidgetSelected->addItem(item->text());
        m_selectedMap[
            ui->listWidgetSelected->item(
            ui->listWidgetSelected->count()-1
            )
        ]=m_selecttingMap[item];
    }
}

void OutputData::onPushButtonClearClicked()
{
    ui->listWidgetSelected->clear();
    m_selectedMap.clear();
}

void OutputData::onPushButtonRemoveClicked()
{
    auto item = ui->listWidgetSelected->currentItem();
    if(!item){
        return;
    }
    int row = ui->listWidgetSelected->row(item);
    ui->listWidgetSelected->takeItem(row);
    delete item; // 释放内存
    m_selectedMap.remove(item);
}

void OutputData::onPushButtonExportClicked()
{
    auto filePath=QFileDialog::getSaveFileName(this,tr("选择保存文件"),"","CSV(*.csv);;Excel(*.xlsx)");
    if(filePath.isEmpty()){
        return;
    }
    bool ret =false;
    if(filePath.endsWith("csv")){
        ret=writeCSV(filePath);
    }else{
        ret=writeXlsx(filePath);
    }
    if(!ret){
        QMessageBox::critical(this, "错误", "保存失败");
    }else{
        QMessageBox::information(this, "提示", "保存成功");
    }
}

bool OutputData::writeCSV(const QString &filePath)
{
    QFile file(filePath);
    file.open(QFile::WriteOnly);
    if(!file.isOpen()){
        return false;
    }
    QTextStream stream = QTextStream(&file);
    int count = ui->listWidgetSelected->count();
    QVector<ElementTreeItem*>list;
    int maxCount=0;
    for(int i=0;i<count;++i){
        list.append(m_selectedMap[ui->listWidgetSelected->item(i)]);
        maxCount = fmax(maxCount,list[i]->data().count());
        if(i<count-1)
            stream<<ui->listWidgetSelected->item(i)->text()<<",";
        else
            stream<<ui->listWidgetSelected->item(i)->text()<<"\n";
    }
    for(int i=0;i<maxCount;++i){
        for(int j=0;j<count;++j){
            if(i<list[j]->data().count()){
                stream<<list[j]->data()[i];
            }
            if(j<count-1)
                stream<<",";
            else
                stream<<"\n";
        }
    }
    stream.flush();
    return true;
}

bool OutputData::writeXlsx(const QString &filePath)
{
    QXlsx::Document xlsx(filePath);
    int count = ui->listWidgetSelected->count();
    QVector<ElementTreeItem*>list;
    int maxCount=0;
    for(int i=0;i<count;++i){
        list.append(m_selectedMap[ui->listWidgetSelected->item(i)]);
        maxCount = fmax(maxCount,list[i]->data().count());
        if(!xlsx.write(1,i+1,ui->listWidgetSelected->item(i)->text())){
            xlsx.save();
            return false;
        }
    }
    for(int i=0;i<maxCount;++i){
        for(int j=0;j<count;++j){
            if(i<list[j]->data().count()){
                if(!xlsx.write(i+2,j+1,list[j]->data()[i])){
                    xlsx.save();
                    return false;
                }
            }
        }
    }
    return xlsx.save();
}
